/*
    Created by IntelliJ IDEA.
    @Auther: gaozhe
    @Date: 2020/4/24 下午 1:42
    
*/
package gaozhe;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

public class HttpDownload {

    public static void main(String[] args) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        System.out.printf("请输入音乐的http地址:");
        String msg = new Scanner(System.in).next();

        try {
            URL url = new URL(msg);
            connection = (HttpURLConnection) url.openConnection();
            inputStream = connection.getInputStream();
            //获取文件名
            String fileName = url.getFile().substring(Integer.parseInt(String.valueOf(url.getFile().toString().lastIndexOf("/"))));
            //创建新文件
            fileOutputStream = new FileOutputStream(new File("C:\\Users\\111\\Desktop\\"+fileName));
            byte[] buffer = new byte[1024];
            int len;
            while ((len=inputStream.read(buffer))!=-1){
                //写数据
                fileOutputStream.write(buffer,0,len);
            }
        } catch (Exception e) {
            System.err.println("您输入的http地址不正确！");
            e.printStackTrace();
        }finally {
            if (fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection !=null){
                connection.disconnect();
            }
        }
    }
}
